from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from users.models import User


class AdminSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('__all__')
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        # 添加管理员字段
        validated_data['is_staff'] = True
        # 调用父类方法创建管理员用户
        admin = super().create(validated_data)
        admin.set_password(validated_data['password'])
        admin.save()
        return admin

    def update(self, instance, validated_data):
        instance = super().update(instance,validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

